package com.xiangxiao.rpan.data.producer.impl;

import com.alibaba.fastjson.JSONObject;
import com.xiangxiao.rpan.data.constant.GlobalConsts;
import com.xiangxiao.rpan.data.consumer.IConsumerAuthorityClient;
import com.xiangxiao.rpan.data.dto.MqttFileUploadDto;
import com.xiangxiao.rpan.data.dto.MqttFloderUploadDto;
import com.xiangxiao.rpan.data.dto.QueryUsersByTopicDto;
import com.xiangxiao.rpan.data.enums.MessageTypeEnum;
import com.xiangxiao.rpan.data.model.BaseAlarm;
import com.xiangxiao.rpan.data.model.FileDownLoadAlarm;
import com.xiangxiao.rpan.data.model.FileUploadAlarm;
import com.xiangxiao.rpan.data.model.FloderUploadAlarm;
import com.xiangxiao.rpan.data.mqtt.MyMqttServer;
import com.xiangxiao.rpan.data.producer.AlarmProduce;
import com.xiangxiao.rpan.data.service.AlarmInfoService;
import com.xiangxiao.rpan.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2024/5/11 15:46
 */
@Component
@Slf4j
public class FloderUploadAlarmProduce implements AlarmProduce<FloderUploadAlarm>  {
  @Autowired
  private AlarmInfoService alarmInfoService;

  @Autowired
  private IConsumerAuthorityClient consumerAuthorityClient;

  public FloderUploadAlarmProduce() {
    super();
  }

  @Override
  public MessageTypeEnum getMessageTypeEnum() {
    return MessageTypeEnum.FLODERUPLOAD;
  }

  @Override
  public void alarm(FloderUploadAlarm m) {
    Integer alarmId = saveAlarm(m);
    if (alarmId == null) {
      log.error("接受告警-保存告警失败，targetId:{}", m.getId());
      return;
    };
    m.setId(alarmId);
    List<String> mqttTopicPrefix = getMqttTopicPrefix(m);
    Set<Integer> sendUserIdList = getSendUserIdList(m);
    System.out.println("发送的用户id列表为:");
    System.out.println(sendUserIdList);
    if (CollectionUtils.isEmpty(sendUserIdList)) {
      log.info("接受告警-无对应的告警发送人,告警信息:{}", JSONObject.toJSONString(m));
    };
    sendUserIdList.forEach(userId -> {
      sendAlarmMq(m, mqttTopicPrefix, userId);
    });
  }

  private void sendAlarmMq(FloderUploadAlarm m, List<String> mqttTopicPrefix, Integer userId) {
    mqttTopicPrefix.forEach(topic -> {
      if (!sendMQTTBefore(m)) {
        return;
      }
      sendMQTT(topic + "/" + userId, m);

    });

    sendMqttAfter(m, userId);
  }

  @Override
  public Integer saveAlarm(FloderUploadAlarm floderUploadAlarm) {
    Integer id = alarmInfoService.insertFloderUploadAlarm(floderUploadAlarm);
    return id;
  }

  @Override
  public boolean sendMQTTBefore(FloderUploadAlarm floderUploadAlarm) {
    return true;
  }

  @Override
  public void sendMQTT(String topic, FloderUploadAlarm floderUploadAlarm) {
    MyMqttServer.post(topic, JSONObject.toJSONString(coverAlarmToMqttData(floderUploadAlarm)));
  }

  @Override
  public void sendMqttAfter(FloderUploadAlarm floderUploadAlarm, Integer userId) {

  }

  @Override
  public Set<Integer> getSendUserIdList(FloderUploadAlarm floderUploadAlarm) {
    Set<Integer> userIdSet = new HashSet<>();
//    userIdSet.add(1);
//    userIdSet.add(11);
//    userIdSet.add(14);
    try {
      QueryUsersByTopicDto dto = new QueryUsersByTopicDto();
      dto.setTopic(GlobalConsts.ALARM_PREFIX + floderUploadAlarm.getMessageType().getMqttTopic());
      System.out.println(dto.toString());
      JSONObject resp = consumerAuthorityClient.queryUserIdsByTopic(dto);
      List<Integer> ids = resp.getJSONArray("data").toJavaList(Integer.class);
      userIdSet = new HashSet<Integer>(ids);
      return userIdSet;
    } catch (RuntimeException e) {
      e.printStackTrace();
      return userIdSet;
    }
  }

  @Override
  public List<String> getMqttTopicPrefix(FloderUploadAlarm floderUploadAlarm) {
    return Collections.singletonList(floderUploadAlarm.getMessageType().getMqttTopic());
  }

  @Override
  public Object coverAlarmToMqttData(FloderUploadAlarm alarm) {
    SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.FORMAT_DATETIME_CN);
    MqttFloderUploadDto dto = new MqttFloderUploadDto();
    List<MqttFileUploadDto> childs = new ArrayList<>();

    for (int i = 0; i < alarm.getChildList().size(); i ++) {
      FileUploadAlarm fileAlarm = alarm.getChildList().get(i);
      MqttFileUploadDto fileDto = new MqttFileUploadDto();
      BeanUtils.copyProperties(fileAlarm, fileDto);
      childs.add(fileDto);
    };

    dto.setId(alarm.getId());
    dto.setType(alarm.getType());
    dto.setTime(sdf.format(alarm.getTime()));
    dto.setStatus(alarm.getStatus().getCode());
    dto.setFloderPath(alarm.getFloderPath());
    dto.setChildList(childs);
    dto.setOperator(alarm.getOperator());
    if (alarm.getStartTime() != null) {
      dto.setStartTime(sdf.format(alarm.getStartTime()));
    };
    if (alarm.getFinishTime() != null) {
      dto.setFinishTime(sdf.format(alarm.getFinishTime()));
    };
    return dto;
  }
}
